package com.hg.concurent.demo5;

import cn.hutool.core.util.RandomUtil;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


public class CountDownLatchDemo {

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch startLatch = new CountDownLatch(1);
		CountDownLatch downLatch = new CountDownLatch(5);

		for (int i = 0; i < 5; i++) {
			new Thread(new worker(startLatch,downLatch),"线程:"+i).start();
		}
		TimeUnit.SECONDS.sleep(1); //休眠1秒,保证所有线程已经调用了await方法
		System.out.println("所有任务都已启动");
		startLatch.countDown();
		System.out.println("等待所有任务完成");
		downLatch.await();
		System.out.println("所有任务完成");
	}
}

class worker implements Runnable{

	private CountDownLatch startLatch;
	private CountDownLatch downLatch;

	public worker(CountDownLatch startLatch, CountDownLatch downLatch) {
		this.startLatch = startLatch;
		this.downLatch = downLatch;
	}
	@Override
	public void run(){
		System.out.println(Thread.currentThread().getName()+"准备工作完成");
		try {
			startLatch.await(); //等待所有工人准备完毕后再开始工作
		} catch (Exception e) {
			e.printStackTrace();
		}
		work();
		try {
			System.out.println(Thread.currentThread().getName()+"工作完成");
			downLatch.countDown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void work() {
		System.out.println(Thread.currentThread().getName()+"开始工作");
		try {
			TimeUnit.SECONDS.sleep(RandomUtil.randomInt(5));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}